var express = require('express');
var request = require('request');
var router = express.Router();

var User = require('../models/admin');
var Blog = require('../models/blog');
var Note = require('../models/note');
var Tag = require('../models/tag');

/* get home page. */
router.get('/', function(req, res, next) {
	Blog.get(0,10,function(err,results){
		res.render('default/', { title: 'XiaoBo',blogs:results});
	})
});

/* get blog detail page. */
router.get('/detail', function(req, res, next) {
	var url =req.protocol+'://' +req.hostname + ':3400' +req.url;
	request('http://api.duoshuo.com/threads/counts.json?short_name=qinxb&threads='+req.query.id,function(error,response,body){
				console.log(body);
		        var articleId = req.query.id;
				body = JSON.parse(body);
				console.log(body);
				console.log(body.response);
	}
	);
	Blog.getById(req.query.id,function(err,blogs){
		res.render('default/detail', { title: 'XiaoBo - Detail',blog:blogs[0],url:url});
	});
});

/* get tag page. */
router.get('/tag', function(req, res, next) {
	Blog.get(0,10,function(err,results){
		Tag.get(function(err,tags) {
			res.render('default/tag', {title: 'XiaoBo - Tag', blogs: results,tags:tags});
		});
	})
});

/* get classify page. */
router.get('/leave-word', function(req, res, next) {
	Note.get(0,10,function(err,resuts){
		console.log(resuts);
		res.render('default/leave-word', { title: 'XiaoBo - Classify',notes:resuts});
	});
});

/* save note action. */
router.post('/note', function(req, res, next) {
	var  note = new Note(req.body);
	note.save(function(err, result){
		res.redirect('/leave-word');
	 });
});

/* get login page. */
router.get('/login', function(req, res, next) {
	res.render('default/login', { title: 'XiaoBo - login' });
});

/*  login action. */
router.post('/tologin', function(req, res, next) {
	console.log(req.body);
	User.login(req.body.username,req.body.password,function (err, user) {
	 if(user){
		 req.session.user = user;
		 res.redirect('/');
	   }
	 });
});

/* get blog-add page. */
router.get('/blog-add',checkLogin);
router.get('/blog-add', function(req, res, next) {
	Tag.get(function(err,results){
		console.log(results);
		res.render('default/blog-add', { title: 'XiaoBo - add',tags:results });
	});
});

/* save blog action */
router.post('/blog-save',checkLogin);
router.post('/blog-save', function(req, res, next) {
	var  blog = new Blog(req.body);
	blog.save(function(err, result){
		console.log(result);
		res.redirect('/');
	});
});

/** check login */
function  checkLogin(req, res, next) {
	if (!req.session.user) {
		return  res.redirect('/login');
	}
	next();
}

module.exports = router;
